<?php
/**
 * Created by PhpStorm.
 * User: CQH
 * Date: 2017/8/30
 * Time: 10:00
 */

namespace app\administrative\controller;

//use think\Cache;
use think\Controller;
use app\common\model\Customer;
use app\common\model\CustomerAdministrativeCenter;
use app\common\model\Contract;
use think\Exception;
use think\Request;
use think\Db;
use app\common\model\CustomerLog;
use app\common\model\Administrative;

/*
 * 客户管理  行政中心
 */
class Customerinfo extends Base{
	
	protected  $Customer;
	protected  $Cacenter;
	protected  $Customerlog;
	protected  $adinfo;
	public function __construct(){
		parent::__construct();
		//实例化客户model
		$this->Customer = new Customer();
		$this->Cacenter = new CustomerAdministrativeCenter();
		$this->Customerlog = new CustomerLog();
		$this->adinfo = new Administrative();
	}
	
	/**
     * 客户列表
     * @Request array    $request     GET   搜索条件(一维数组)
     * @return array
     */
	public function index(){
		//Cache::clear();
        //处理条件
        $request = input('');
        $where = array();
        $search = array(
        	'username'=>'',
        	'tel'=>'',
            'telphone'=>'',
            'id_card'=>'',
            'remark'=>'',
        );
        foreach ($request as $key => $value){
            $search[$key] = $value;
            if (empty($value)){
                continue;
            }
            if ($key == 'username'){
            	$where['username'] = ['like','%'.$value.'%'];
            	continue;
            }
            if ($key == 'tel'){
                $where['rq_customer.telphone'] = $value;
                continue;
            }
            if ($key == 'remark'){
                $where['rq_customer.remark'] = ['like','%'.$value.'%'];
                continue;
            }
            if ($key == 'user_type'){
                $where['rq_customer.'.$key] = $value;
                continue;
            }
            if ($key == 'is_entry'){
                $where['rq_customer.'.$key] = $value;
                continue;
            }
            if ($key == 'operation_id'){
                $where['rq_customer.'.$key] = $value;
                continue;
            }
            if ($key == 'administrative_id'){
                $where['rq_customer_administrative_center.'.$key] = $value;
                continue;
            }
            $where[$key] = $value;
        }
        
        $where['administrative_id'] = session($this->set['db_name'].'a_id');
        //获取数据
        $data = $this->Customer->selectPage($where);
        //当前用户所属行政中心
        $aid = session($this->Customer->sdb_name.'a_id');
        //获取运营中心
        $oid=db('administrative_info')->where(['a_id'=>$aid])->value('operation');
        $operation = $this->Customer->selectOperationInfo(array('op.o_id'=>$oid));
//        for ($i=count($operation); $i >= 0; $i--) {
//            if($i>=1){
//                if($operation[$i]=$operation[$i-1]){
//                    unset($operation[$i]);
//                }
//            }
//        }
        //获取行政中心
        $administrative = $this->Customer->selectAdministrativeInfo(array('a_id'=>$aid));
        $ainfo=$administrative;
        

        //模板赋值
        $this->assign('Nowpage', $data['page']['currentPage']); //当前页
        $this->assign('allpage', $data['page']['lastPage']); //总页数
        $this->assign('count', $data['page']['count']);//总条数
        $this->assign('search',$search);
        $this->assign('operation',$operation);
        $this->assign('administrative',$administrative);
        $this->assign('ainfo',$ainfo);
        $this->assign('data',$data['data']);
        if(input('get.page')){
            return json($data);
        }
        //渲染模板
        return $this->fetch('admin@customer:index');
	}
	
	
	/**
	 * 删除客户     逻辑删除
	 * @Request user_id             int    GET   客户ID
	 * @return array
	 */
	public function delete()
	{
		//检验get参数
		if (input('?get.data')){
			//获取参数并强制转换为int型
			$user_id = input('')['data'];
		}else{
			return json(array('code'=>0,'msg'=>'缺少必要参数'));
		}
	
		foreach ($user_id as $key => $value){
			if ($value == 'on'){
				continue;
			}
	
			$checkData = $this->Customer->selectOne(array('user_id'=>intval($value)));
	
			if (empty($checkData)){
				return json(array('code'=>0,'msg'=>"删除失败"));
			}
			$res = $this->Customer->deleteOne($value);
			if($res === false){
				return json(array('code'=>0,'msg'=>'删除失败'));
			}
		}
		return json(array('code'=>1,'msg'=>'删除成功'));
	}
	
	
    /**
     * 查看用户详情
     * @Request user_id             int    GET   用户ID
     * @return array
     */
    public function details()
    {
    	
    	$where = array();
        //检验get参数
        if (input('?get.user_id')){
            //获取参数并强制转换为int型
            $where['rq_customer.user_id'] = input('get.user_id/d');
        }else{
            return json(array('code'=>0,'msg'=>'缺少必要参数'));
        }
        
        //获取数据
        $info = $this->Customer->findOne($where);
        $log = $this->Customerlog->getList(array('customer_id'=>$info['user_id']));//行政中心查看log
        if ($log){
        	foreach ($log as $k=>$v){
        		$t = $log[$k]['add_time'];
        		$log[$k]['add_time'] = date("Y-m-d H:i:s",$t);
        	}
        	$this->assign('log',$log);
        }

       	//$info[0]['uid'] = session($this->set['db_name'].'uid');
       	//$info[0]['name'] = session($this->set['db_name'].'username');
       	//$info[0]['rolename'] = session($this->set['db_name'].'rolename');

       	/*
       	 * 合同
       	 * @author  ligang
       	 */
        $Contract = new Contract();
        $ContractWhere['user_id'] = $where['rq_customer.user_id'];
        $ContractWhere['is_delete'] = 0;
        $ContractArray = $Contract->selectData($ContractWhere,'contract_id,contract_no,installed_time');
        $i = 1;
        foreach ($ContractArray as $key =>$value){
            $ContractArray[$key]['No'] = $i;
            $ContractArray[$key]['EquipmentNumber'] = $Contract->getEquipmentNumber(['contract_id'=>$value['contract_id'],'state'=>1,'is_delete'=>0]);
            $ContractArray[$key]['installed_time'] = date('Y.m.d',$value['installed_time']);
            $i++;
        }
        $this->assign('Contract',$ContractArray);
       	//---------------------
        $this->assign('info',$info);
        

        //渲染模板
        return $this->fetch('admin@customer:details');

    }
	
    /**
     * 显示新增客户页面
     * @Request user_id             int    GET   客户ID
     * @return array
     */
    public function add()
    {
        //当前用户所属行政中心
        $aid = session($this->Customer->sdb_name.'a_id');
    	//Cache::clear();
    	//获取运营中心
        $oid=db('administrative_info')->where(['a_id'=>$aid])->value('operation');
        $operation = $this->Customer->selectOperationInfo(array('op.o_id'=>$oid));
    	//获取行政中心
    	$administrative = $this->Customer->selectAdministrativeInfo(array('a_id'=>$aid));
    	//获取地址
    	$province = $this->Customer->areasProvince(array('id'=>$administrative[0]['province_id']));
    	$city = $this->Customer->areasCity($administrative[0]['province_id']);
    	$area = $this->Customer->areaName($administrative[0]['city_id']);
    	
    	//获取客户配置信息
    	$status = config('account_status');
    	$nature = config('nature');
    	$housing_property = config('housing_property');
    	$is_entry = config('is_entry');
    	$user_type = config('user_type');
    	unset($is_entry['3']);
    	
    	$this->assign('operation',$operation);
    	$this->assign('administrative',$administrative);
    	
    	$this->assign('province',$province);
    	$this->assign('city',$city);
    	$this->assign('area',$area);
    	
    	$this->assign('status',$status);
    	$this->assign('nature',$nature);
    	$this->assign('housing_property',$housing_property);
    	$this->assign('is_entry',$is_entry);
    	$this->assign('user_type',$user_type);

    	//渲染模板
        return $this->fetch('admin@customer:add_user');
    }	 
    
    /**
     * 处理 新增客户信息       （没有离职状态）                   
     * @Request user_id             int    GET   客户ID
     * @return array
     */
    public function doadd()
    {

    	//检验提交数据
    	$data = $this->request->post();
    	//去除空格
    	foreach ($data as $k=>$v){
    		$data[$k] = preg_replace("/\s|　/","",$v);
    	}
    	if(empty($data['account_status'])) {
            return ['code' => 0, 'msg' => '账户状态不能为空'];
        }
    	//验证数据
        $vRet = $this->Customer->valli($data);
    	if($vRet!==true){
    	    return json($vRet);
        }

        //给运营中心和行政中心固定值
        $a_id = session($this->set['db_name'].'a_id');
        $info = $this->adinfo->findOne(array("a_id"=>$a_id));
        $data['operation_id'] = $info['operation'];
       
    	//处理数据
    	$data['birthday']=strtotime(substr($data['id_card'],6,8));
    	$data['avatar_img']='';
    	$data['add_time'] = time();
    	//获取地址名
        $areaInfo = db('areas')->where('id','in',[$data['province_code'],$data['city_code'],$data['area_code']])->select();
        $data['province'] = $areaInfo[0]['area_name'];
        $data['city'] = $areaInfo[1]['area_name'];
        $data['area'] = $areaInfo[2]['area_name'];
    	unset($data['a_id']);
    	//判断是否入职
    	if ($data['is_entry']==1){
    		Db::startTrans();
    		try{
                //入职
                $data['personnel_time']=strtotime($data['personnel_time']);
                $customInfo = Db::name('personnel_number')->where(array('personnel_number'=>$data['employee_id']))->find();
                if($customInfo){
                    return json(array('code'=>-1,'msg'=>'员工编号已经存在','data'=>''));
                }
                $re=Db::name('personnel_number')->insert(['personnel_number'=>$data['employee_id'],'personnel_time'=>$data['personnel_time']]);
                unset($data['personnel_time']);
                $user_id=$this->Customer->insertOne($data);
                $res=$this->Cacenter->insertOne(array('user_id'=>$user_id,'administrative_id'=>$a_id));
                DB::commit();
                if ($res == 0){
                    //日志
                    return json(array('code'=>0,'msg'=>'新增失败','data'=>''));
                }else{
                    //日志
                    return json(array('code'=>1,'msg'=>'新增成功','data'=>url('Customerinfo/index')));
                }
            }catch (Exception $e){
    		    DB::rollback();
                return json(array('code'=>0,'msg'=>'新增失败','data'=>''));
            }
    	}else{
    		//客户
            Db::startTrans();
            try{
                unset($data['personnel_time']);
                $user_id=$this->Customer->insertOne($data);
                $res=$this->Cacenter->insertOne(array('user_id'=>$user_id,'administrative_id'=>$a_id));
                Db::commit();
                if ($res == 0){
                    //日志
                    return json(array('code'=>0,'msg'=>'新增失败','data'=>''));
                }else{
                    //日志
                    return json(array('code'=>1,'msg'=>'新增成功','data'=>url('Customerinfo/index')));
                }
            }catch (Exception $e){
                Db::rollback();
                return json(array('code'=>0,'msg'=>'新增失败','data'=>''));
            }

    	}
    }
    
    
    
    /**
     * 修改客户信息   回显                 
     * @Request user_id             int    GET   客户ID
     * @return array
     */
    public function update()
    {
    	//Cache::clear();
    	$id = input('get.user_id/d');
    	$where = array('rq_customer.user_id' => $id,'rq_administrative_info.a_id'=>session($this->set['db_name'].'a_id'));
    	$info = $this->Customer->findOne($where);
    	if(!$info){
    	    $this->error('数据错误');
        }
    	$this->assign('info',$info);

        //当前用户所属行政中心
        $aid = session($this->Customer->sdb_name.'a_id');
        //获取运营中心
        $oid=db('administrative_info')->where(['a_id'=>$aid])->value('operation');
        $operation = $this->Customer->selectOperationInfo(array('op.o_id'=>$oid));
//        for ($i=count($operation); $i >= 0; $i--) {
//            if($i>=1){
//                if($operation[$i]=$operation[$i-1]){
//                    unset($operation[$i]);
//                }
//            }
//        }
            
        //获取行政中心
        $administrative = $this->Customer->selectAdministrativeInfo(array('a_id'=>$aid));


        // 获取用户信息
        $mbwhere['user_id'] = $id;
        $memberData = $this->Customer->selectOne($mbwhere);
        // 获取用户的地址
        $province = $this->Customer->areasProvince(array('id'=>$memberData[0]['province_code']));
        $city = $this->Customer->areasCity($memberData[0]['province_code']);
        $area = $this->Customer->areaName($memberData[0]['city_code']);

        //获取地址
//        $province = $this->Customer->areasProvince(array('id'=>$administrative[0]['province_id']));
//        $city = $this->Customer->areasCity($administrative[0]['province_id']);
//        $area = $this->Customer->areaName($administrative[0]['city_id']);

        //获取客户配置信息
    	$status = config('account_status');
    	$nature = config('nature');
    	$housing_property = config('housing_property');
        $is_entry = config('is_entry');
        if(!empty($info['employee_id']) && $info['is_entry'] == '入职'){
            unset($is_entry);
            $is_entry = config('is_entry');
            foreach ($is_entry as $k => $v) {
                if($v=='客户'){
                    unset($is_entry[$k]);
                }
            }
        }
        if(!empty($info['departure_time']) && $info['is_entry'] == '离职')
        {
            unset($is_entry);
            $is_entry = config('is_entry');
            foreach ($is_entry as $k => $v) {
                if($v=='离职'){
                    unset($is_entry[$k]);
                }
            }
        }
        $ty=db('customer')->where(['user_id'=>$id])->value('is_entry');
        if($ty==2){
            unset($is_entry);
            $is_entry = config('is_entry');
            foreach ($is_entry as $k => $v) {
                if($v=='离职'){
                    unset($is_entry[$k]);
                }
            }
        }
        $user_type = config('user_type');
        $this->assign('operation',$operation);
        $this->assign('administrative',$administrative);
        
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        
        $this->assign('status',$status);
        $this->assign('nature',$nature);
        $this->assign('housing_property',$housing_property);
        $this->assign('is_entry',$is_entry);
        $this->assign('user_type',$user_type);

        //渲染模板
        return $this->fetch('admin@customer:update_user');

    }

    /**
     * 修改客户信息     
     * @Request user_id             int    GET   客户ID
     * @return array
     */
    public function doupdate()
    {

    	//Cache::clear();
    	$where = array();
    	//检验提交数据
    	$data = $this->request->post();

        //获取客户配置信息
        $status = config('account_status');
        $nature = config('nature');
        $housing_property = config('housing_property');
        $is_entry = config('is_entry');
        $user_type = config('user_type');

        //转换客户配置信息状态
        $data['account_status'] = $status[$data['account_status']];
//        $data['nature'] = $nature[$data['nature']];
//        $data['housing_property'] = $housing_property[$data['housing_property']];
        $data['is_entry'] = $is_entry[$data['is_entry']];
//        $data['user_type'] = $user_type[$data['user_type']];

//        dump($data);die();
    	//查找原始数据
        $info = $this->Customer->findOne(array('rq_customer.user_id' => $data['user_id']));
        if(!$info){
            return json(array('code'=>0,'msg'=>'数据异常','data'=>''));
        }
        //判断电话号码唯一
//        $sWhere['telphone'] = $data['telphone'];
//        $cuInfo = $this->Customer->findOne($sWhere);
//        if($cuInfo && $cuInfo['user_id'] != $info['user_id']){
//            return json(array('code'=>0,'msg'=>'联系电话已经存在','data'=>''));
//        }
//        //判断身份证号码唯一
//        $idWhere=[
//            'id_card' =>$data['id_card'],
//            'rq_customer.user_id' =>['<>',$data['user_id']]
//        ];
//
//        $cuInfo = $this->Customer->findOne($idWhere);
//        if($cuInfo){
//            return json(array('code'=>0,'msg'=>'身份证已经存在','data'=>''));
//        }
        //去除空格
        foreach ($data as $k=>$v){
            $data[$k] = preg_replace("/\s|　/","",$v);
        }
        $vRet = $this->Customer->valli($data);
        if($vRet!==true){
            return json($vRet);
        }

        //获取地址名
        $areaInfo = db('areas')->where('id','in',[$data['province_code'],$data['city_code'],$data['area_code']])->select();
        $data['province'] = $areaInfo[0]['area_name'];
        $data['city'] = $areaInfo[1]['area_name'];
        $data['area'] = $areaInfo[2]['area_name'];

        //给行政中心固定值
        $a_id = session($this->set['db_name'].'a_id');
        Db::startTrans();
        try{
            foreach ($info as $key=>$val){
                if(isset($data[$key])){
                    if($data[$key]!= $val ){
                        //写入日志
                        $clogData['filename'] = $key;
                        $clogData['old_content'] = $val;
                        $clogData['new_content'] = $data[$key];
                        $clogData['operator_id'] = session($this->set['db_name'].'uid');//管理员ID
                        $clogData['operator_name'] = session($this->set['db_name'].'rolename');//超级管理员
                        $clogData['operator_account'] = session($this->set['db_name'].'username');//admin
                        $clogData['o_id'] = '';
                        $clogData['a_id'] = $a_id;
                        $clogData['terminal_type'] = 1;//终端信息 1为行政中心
                        $clogData['customer_id'] = $info['user_id'];//客户ID
                        $clogData['add_time'] = time();
                        $this->Customerlog->insertOne($clogData);
                    }
                }

            }
            //处理数据
            $data['birthday']=strtotime($data['birthday']);
            if ($data['is_entry'] == 1 && $info['is_entry']!="入职") {
                $data['personnel_time'] = strtotime($data['personnel_time']);
            }
            unset($data['a_id']);
            //更新操作
            $where['user_id'] = $data['user_id'];
            //写入员工编号
            if ($info['is_entry']!="入职" && $data['is_entry']=='入职'){
                $personnel_number = Db::table('rq_customer')->where(['employee_id'=>$data['employee_id']])->field('employee_id')->find();
                if (!empty($personnel_number)){
                    return json(array('code' => 0, 'msg' => '员工编号已存在', 'data' => ''));
                }
                Db::name('personnel_number')->insert(['personnel_number'=>$data['employee_id'],'personnel_time'=>strtotime($data['personnel_time'])]);
            }
            if ($info['is_entry']!="离职" && $data['is_entry']==3){
                $idata['user_id'] =  $info['user_id'];
                $idata['employee_id'] =  $info['employee_id'];
                $idata['departure_time'] =  strtotime($data['departure_time']);
                Db::name('departure_time_log')->insert($idata);
            }

            unset($data['personnel_time']);
            if(isset($data['departure_time'])){
                $data['departure_time'] = strtotime($data['departure_time']);
            }
            $is_entry = ['入职' => 1, '客户' => 2, '离职' => 3];
            $account_status = ['正常' => 1, '冻结' => 2];
            $data['is_entry'] = $is_entry[$data['is_entry']];
            $data['account_status'] = $account_status[$data['account_status']];

            $this->Customer->updateOne($where,$data);
            $this->Cacenter->updateOne($where,array('administrative_id'=>$a_id));
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(array('code'=>0,'msg'=>$e->getMessage(),'data'=>''));
        }

        // 判断客户是否离职
        if ($data['is_entry'] == 3) {
            $post_data['number'] = $data['employee_id'];
            // 业绩系统
            $url = config('post_entry_api');
            // 调用post_request发送请求
            $curResult = post_request($url, $post_data);
            $ApiResult = json_decode($curResult);
            if ($ApiResult->code == 1){
                return json(array('code'=>1,'msg'=>'迁移成功','data'=>url('Customerinfo/index')));
            }else{
                return json(array('code'=>1,'msg'=>'迁移失败','data'=>url('Customerinfo/index')));
            }
        }

        return json(array('code'=>1,'msg'=>'修改成功','data'=>url('Customerinfo/index')));

    }

	/**
	 * 根据运营中心获取行政中心
	 * @Request operation_id             int    GET  
	 * @return array
	 */
	public function selectAdministrative()
	{
		$where = array();
		if(input('get.operation/d')){
			$where['operation'] = input('get.operation/d');
		}
		$administrative = $this->Customer->selectAdministrativeInfo($where);
		return $administrative;
	}

	/*
	 * 获取更多修改日志
	 */
	public function getUserLog(){
		//Cache::clear();
		$page = input('page');
		$limit = ($page*5).",".(5);
		$where['customer_id'] =  input('uid');
		$order="add_time desc";
		$listInfo = $this->Customerlog->getList($where,$order,$limit);
		if(!$listInfo){
			$data['code'] = 0;
			return json($data);
		}
		if ($listInfo){
			foreach ($listInfo as $k=>$v){
				$t = $listInfo[$k]['add_time'];
				$listInfo[$k]['add_time'] = date("Y-m-d H:i:s",$t);
			}
		}
		$data['page'] = $page+1;
		$data['data'] = $listInfo;
		$data['code'] = 1;
		return json($data);
	}

	//推荐设备详情
    public function devicedetails(){
	    $cid = input('cid');
	    $type = input('type',0);
	    $introducerInfo = \db('customer')->where(['user_id'=>$cid])->find();

	    if ($introducerInfo['is_entry'] == 1){
        //入职
            //获取入职时间
            $entry_time = Db::name('personnel_number')->where(['personnel_number'=>$introducerInfo['employee_id']])->field('personnel_time')->find()['personnel_time'];
            $cInfo = db('contract')
                ->where(array('co.introducer_id'=>$cid,'co.add_time'=>['<=',$entry_time]))
                ->alias('co')
                ->join('rq_customer cu','co.introducer_id=cu.user_id')
                ->select();
	    }
	    if ($introducerInfo['is_entry'] == 3){
            //离职
            $entry_time = Db::name('personnel_number')->where(['personnel_number'=>$introducerInfo['employee_id']])->field('personnel_time')->find()['personnel_time'];
            $leave_date = $introducerInfo['departure_time'];
            $where = [
                'co.introducer_id'=>$cid,
                'co.add_time'=>['NOT BETWEEN',[$entry_time,$leave_date]]
            ];
            $cInfo = db('contract')
                ->where($where)
                ->alias('co')
                ->join('rq_customer cu','co.introducer_id=cu.user_id')
                ->select();
        }

        if ($introducerInfo['is_entry'] == 2){
            $cInfo = db('contract')
                ->where(array('co.introducer_id'=>$cid,'is_entry'=>['<>',1]))//
                ->alias('co')
                ->join('rq_customer cu','co.introducer_id=cu.user_id')
                ->select();
        }

	    $data = array();
	    $count = 0;
	    foreach ($cInfo as $key=>$val){
            $contract_id = $val['contract_id'];
            $temp =  db('contract_equipment')
                ->join([['rq_contract','rq_contract_equipment.contract_id = rq_contract.contract_id'],['rq_customer','rq_customer.user_id = rq_contract.user_id']])
                ->where(array('rq_contract_equipment.contract_id'=>$contract_id,'is_Discount'=>$type))
                ->field('id,telphone,username,rq_contract_equipment.contract_id,equipments_number,is_Discount,Discount_time,Discount_people')
                ->select();
            foreach ($temp as $k=>&$v){
//                $v['telphone'] = $val['telphone'];
                $v['contract_no'] = $val['contract_no'];
            }
            $data[] = $temp;
        }
        //计算有效设备数
        foreach ($cInfo as $key=>$val){
            $contract_id = $val['contract_id'];
            $temp =  db('contract_equipment')->where(array('contract_id'=>$contract_id,'is_Discount'=>0))->count();
            $count +=$temp;
        }
        $admin=1;//判断是否为行政中心
        //显示备注 操作记录 当前用户所有记录
        $userR=db('recommend_equipment_log')->where(array('uid'=>$cid))->select();
        $this->assign('count',$count);
        $this->assign('type',$type);
        $this->assign('cid',$cid);
        $this->assign('isAdmin',$admin);
        $this->assign('userR',$userR);
        $this->assign('list',$data);
        return $this->fetch('admin@customer:device_details');

    }
    //推荐设备

    /**
     * @return \think\response\Json
     */
    public function recommend(){
       $tem=$this->request->get();
       $text=input('log');
       $id=explode(",",$tem['id']);
       $count_t=0;//计数
       $co_no='';//合同编号
       $nam_t='';//用户名
       $admin=session($this->set['db_name'].'username');//获取当前管理员姓名
       if(!empty($tem)){
           foreach ($id as $v){
               $temp[]=db('contract_equipment')->where(array('id'=>$v))->find();//设备编号
           }
           foreach ($temp as $k=>$v){
               $co_tem[]=db("contract")->where(array('contract_id'=>$temp[$k]['contract_id']))->find();
               $co_no.='合同'.$co_tem[$k]['contract_no'].'('.$temp[$k]['equipments_number'].') ';//合同编号
//               $introducer_id[]=$co_tem[$k]['introducer_id'];//推荐人id
               $user_id[]=$co_tem[$k]['user_id'];//推荐会员id
               $count_t++;
           }
           $introducer=$co_tem[0]['introducer_id'];//推荐人id
           $usname_t=db('customer')->where(array('user_id' => $introducer))->find();
           $username=$usname_t['username'];//用户姓名
           if($count_t==1){//单条数据
               $name_t=db('customer')->where(array('user_id' => $user_id[0]))->find();
               $name=$name_t['username'];//推荐会员名
               $data=[
                   'uid' => $introducer,
                   'username' => $username,
                   'admin' => $admin,
                   'name' => $name,
                   'usedtime' => time(),
                   'log' => $co_no.$text
               ];
               //dump($data);exit;
               $res_log = db('recommend_equipment_log')->insert($data);
           }else {//多条数据
               foreach ($user_id as $k => $v) {
                   $introducer_t[] = db('customer')->where(array('user_id' => $user_id[$k]))->find();
                   $nam_t .= $introducer_t[$k]['username'].' ';//推荐会员名
               }
               $data = [
                   'uid' => $introducer,
                   'username' => $username,
                   'admin' => $admin,
                   'name' => $nam_t,
                   'usedtime' => time(),
                   'log' => $co_no.$text
               ];
//               dump($data);exit;
               //插入数据到数据库
              $res_log = db('recommend_equipment_log')->insert($data);
           }

           if(!empty($introducer)){//使用标记
               foreach ($id as $k=>$v){
                   $res = db('contract_equipment')->where('id', $v)->update(['is_Discount' => 1,'Discount_time'=>time(),'Discount_people'=>$admin]);
               }
           }
       }

       if($res&&$res_log){
           //日志
           writelog(session($this->set['db_name'].'a_id'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】修改成功：使用优惠',1,'administrative_log');
           return json(['status' => 1, 'message' => '使用优惠成功！']);
       }else{
           writelog(session($this->set['db_name'].'a_id'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】修改失败：使用优惠',0,'administrative_log');
           return json(['status' => 2, 'message' => '操作失败！']);
       }

    }

    //获取员工编号
    public function getEmployeeNumber(){
        $checkEmployeeNumber = Db::name('personnel_number')->max('personnel_number');
        if (!$checkEmployeeNumber){
            $number = 100001;
            return json(array('number'=>$number));
        }else{
            return json(array('number'=>$checkEmployeeNumber+1));
        }
    }

    /*
    *  入职已审核列表
    *  @author 李港
    */
    public function entryalreadyaudit()
    {
        //处理条件
        $request = input('');
        $where = array();
        $search = array(
            'username'=>'',
            'tel'=>'',
            'telphone'=>'',
            'id_card'=>''
        );
        foreach ($request as $key => $value){
            $search[$key] = $value;
            if (empty($value)){
                continue;
            }
            if ($key == 'username'){
                $where['username'] = ['like','%'.$value.'%'];
                continue;
            }
            if ($key == 'tel'){
                $where['rq_customer.telphone'] = $value;
                continue;
            }
            $where[$key] = $value;
        }

        $where['rq_administrative_user.a_id'] = session($this->set['db_name'].'a_id');
        $where['rq_entry_audit.a_id'] = session($this->set['db_name'].'a_id');
        $where['rq_entry_audit.state'] = ['<>',1];
        if (isset($where['datetimeStart']) || isset($where['datetimeEnd'])){
            if (empty($where['datetimeStart'])){
                $where['datetimeStart'] = 0;
            }else{
                $where['datetimeStart'] = strtotime($where['datetimeStart']);
            }
            if (empty($where['datetimeEnd'])){
                $where['datetimeEnd'] = time();
            }else{
                $where['datetimeEnd'] = strtotime($where['datetimeEnd']) + 3600*24;
            }
            $where['submit_time'] = ['between',[$where['datetimeStart'],$where['datetimeEnd']]];
            unset($where['datetimeStart']);
            unset($where['datetimeEnd']);
        }
        //获取数据
        $join = [
            ['rq_customer','rq_customer.user_id = rq_entry_audit.user_id'],
            ['rq_administrative_user','rq_administrative_user.id = rq_entry_audit.do_id']
        ];
        $field = '
            rq_entry_audit.id,
            rq_entry_audit.state,
            rq_entry_audit.remarks,
            rq_customer.telphone,
            rq_customer.id_card,
            rq_administrative_user.name,
            rq_entry_audit.do_time,
            rq_customer.username
        ';
        $order = 'rq_entry_audit.do_time desc,rq_entry_audit.state ASC';
        $db = 'entry_audit';
        $data = $this->Customer->selectPages($where,$join,$field,$order,$db);

        //转换
        foreach ($data['data'] as $dataKey => $dataValue){
            $data['data'][$dataKey]['do_time'] = date("Y-m-d H:i:s",$dataValue['do_time']);
            switch ($dataValue['state']){
                case 1:
                    $state = "待审核";
                    break;
                case 2:
                    $state = "审核通过";
                    break;
                case 3:
                    $state = "拒绝";
                    break;
                default:
                    $state = "不存在的状态";
            }
            $data['data'][$dataKey]['state'] = $state;
        }

        //模板赋值
        $this->assign('Nowpage', $data['page']['currentPage']); //当前页
        $this->assign('allpage', $data['page']['lastPage']); //总页数
        $this->assign('count', $data['page']['count']);//总条数
        $this->assign('search',$search);
        $this->assign('data',$data['data']);
        if(input('get.page')){
            return json($data);
        }
        return $this->fetch('customer/entryalreadyaudit');
    }

    /*
     *  入职未审核列表
     *  @author 李港
     */
    public function entryaudit()
    {
        //处理条件
        $request = input('');
        $where = array();
        $search = array(
            'username'=>'',
            'tel'=>'',
            'telphone'=>'',
            'id_card'=>''
        );
        foreach ($request as $key => $value){
            $search[$key] = $value;
            if (empty($value)){
                continue;
            }
            if ($key == 'username'){
                $where['username'] = ['like','%'.$value.'%'];
                continue;
            }
            if ($key == 'tel'){
                $where['rq_customer.telphone'] = $value;
                continue;
            }
            $where[$key] = $value;
        }

        $where['a_id'] = session($this->set['db_name'].'a_id');
        $where['rq_entry_audit.state'] = 1;
        if (isset($where['datetimeStart']) || isset($where['datetimeEnd'])){
            if (empty($where['datetimeStart'])){
                $where['datetimeStart'] = 0;
            }else{
                $where['datetimeStart'] = strtotime($where['datetimeStart']);
            }
            if (empty($where['datetimeEnd'])){
                $where['datetimeEnd'] = time();
            }else{
                $where['datetimeEnd'] = strtotime($where['datetimeEnd']) + 3600*24;
            }
            $where['submit_time'] = ['between',[$where['datetimeStart'],$where['datetimeEnd']]];
            unset($where['datetimeStart']);
            unset($where['datetimeEnd']);
        }
        //获取数据
        $join = [
            ['rq_customer','rq_customer.user_id = rq_entry_audit.user_id']
        ];
        $field = '
            rq_entry_audit.id,
            rq_entry_audit.state,
            rq_entry_audit.remarks,
            rq_entry_audit.submit_time,
            rq_customer.telphone,
            rq_customer.id_card,
            rq_customer.username
        ';
        $order = 'rq_entry_audit.submit_time desc,rq_entry_audit.state ASC';
        $db = 'entry_audit';
        $data = $this->Customer->selectPages($where,$join,$field,$order,$db);

        //转换
        foreach ($data['data'] as $dataKey => $dataValue){
            $data['data'][$dataKey]['submit_time'] = date("Y-m-d H:i:s",$dataValue['submit_time']);
            switch ($dataValue['state']){
                case 1:
                    $state = "待审核";
                    break;
                case 2:
                    $state = "审核通过";
                    break;
                case 3:
                    $state = "拒绝";
                    break;
                default:
                    $state = "不存在的状态";
            }
            $data['data'][$dataKey]['state'] = $state;
        }

        //模板赋值
        $this->assign('Nowpage', $data['page']['currentPage']); //当前页
        $this->assign('allpage', $data['page']['lastPage']); //总页数
        $this->assign('count', $data['page']['count']);//总条数
        $this->assign('search',$search);
        $this->assign('data',$data['data']);
        if(input('get.page')){
            return json($data);
        }
        return $this->fetch('customer/entryaudit');
    }

    /*
     *  入职审核操作
     *  @author 李港
     */
    public function doentryaudit()
    {
        $id = input('get.id');
        $type = input('get.type');
        if (empty($id)){
            return json(['code'=>0,'msg'=>'缺少必要参数id']);
        }
        if ($type != 1 && $type != 2){
            return json(['code'=>0,'msg'=>'请求类型不匹配']);
        }
        $do_id = session($this->set['db_name'].'uid');
        $do_time = time();
        Db::startTrans();
        try{
            if ($type == 1){
                $data['state'] = 2;
                //入职操作
                $result = $this->entry($id);
                if ($result['code'] == 0){
                    return json($result);
                }
            }else if ($type == 2){
                $data['state'] = 3;
            }else{
                return json(array('code'=>0,'msg'=>'未知操作'));
            }
            $data['do_id'] = $do_id;
            $data['do_time'] = $do_time;
            Db::name('entry_audit')->where(['id'=>$id])->update($data);
            Db::commit();
            return json(array('code'=>1,'msg'=>'操作成功'));
        }catch (\Exception $e){
            echo $e;
            Db::rollback();
            return json(array('code'=>0,'msg'=>'操作失败'));
        }
    }

    /*
     *  审核通过入职操作
     *  @author 李港
     *  @param int $id  入职审核ID
     */
    public function entry($id)
    {
        //定义返回格式
        $return = [
            'code'=>0,
            'error'=>'',
            'data'=>''
        ];
        if (empty($id)){
            $return['error'] = '不存在的入职审核数据ID';
            return $return;
        }
        //获取当前的入职审核的数据
        $entry_audit_data = Db::name('entry_audit')->where(['id'=>$id])->find();
        if (empty($entry_audit_data)){
            $return['error'] = '不存在的入职审核数据';
            return $return;
        }

        //获取用户的数据
        $user_data = Db::name('customer')->where(['user_id'=>$entry_audit_data['user_id']])->find();
        if (empty($user_data)){
            $return['error'] = '不存在的客户';
            return $return;
        }

        if ($user_data['is_entry'] == 1){
            $return['error'] = '该客户已经是员工';
            return $return;
        }

        //获取当前的员工编号
        $EmployeeNumber = EmployeeNumber();
        //入职的数据
        $entry_data = [
            'user_id'=>$entry_audit_data['user_id'],
            'is_entry'=>1,
            'employee_id'=>$EmployeeNumber,
        ];
        Db::startTrans();
        try{
            if ($EmployeeNumber != EmployeeNumber()){
                $EmployeeNumber = EmployeeNumber();
            }
            Db::name('customer')->update($entry_data);
            $insertData = [
                'personnel_number'=>$EmployeeNumber,
                'personnel_time'=>time()
            ];
            Db::name('personnel_number')->insert($insertData);
            $return['code'] = 1;
            Db::commit();
            return $return;
        }catch (\Exception $e){
            $return['error'] = $e;
            Db::rollback();
            return $return;
        }

    }
}